package com.tech.mapper.tem.imp;

import com.tech.mapper.GoodsImageDao;
import com.tech.repository.entity.GoodsImage;
import com.tech.util.FileUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class GoodsImageMysqlDaoImp extends BasicDaoImp<GoodsImage> implements GoodsImageDao {
	@Override
	public GoodsImage getGoodsImage(int id) {
		return null;
	}

	@Override
	public List<GoodsImage> getGoodsAllImages(int goodsId) {
		SqlTask<Integer, List<GoodsImage>> sqlTask = (item, data) -> {
			String sql = "select * from goodsimage where gid=?";
			ArrayList<GoodsImage> list = new ArrayList<>();
			PreparedStatement statement = item.prepareStatement(sql);
			statement.setInt(1, data);
			ResultSet rs = item.executeQuery();
			while (rs.next()) {
				list.add(getInstance(rs));
			}
			return list;
		};
		return SqlTask.processSql(sqlTask, goodsId);
	}

	@Override
	public TreeMap<Integer, List<GoodsImage>> getAllGoodsImages() {
		return null;
	}

	@Override
	public int addGoodsImage(GoodsImage goodsImage, String suffix) {
		SqlTask<GoodsImage, Integer> sqlTask = (item, data) -> {
			String sql = "insert into goodsimage(gid,image) values (?,?)";
			int newId = -1;
			PreparedStatement statement = item.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			statement.setInt(1, data.getGoodsId());
			statement.setBytes(2, FileUtil.imageToByte(data.getImage(), suffix));
			if (statement.executeUpdate() == 1) {
				ResultSet generatedKeys = item.getGeneratedKeys();
				if (generatedKeys.next()) {
					newId = generatedKeys.getInt(1);
				}
			}
			return newId;
		};
		return SqlTask.processSql(sqlTask, goodsImage);
	}

	@Override
	public int[] addGoodsImages(List<GoodsImage> goodsImageList) {
		return new int[0];
	}

	@Override
	public boolean delGoodsImage(int id) {
		return false;
	}

	@Override
	public int[] delGoodsImage(List<Integer> GoodsImageList) {
		return new int[0];
	}

	@Override
	public int delGoodsGoodsImage(int goodsId) {
		return 0;
	}

	@Override
	public boolean delAllGoodsImage() {
		return false;
	}

	@Override
	protected GoodsImage getInstance(ResultSet rs) throws SQLException {
		return new GoodsImage(rs.getInt("imid"),
				rs.getInt("gid"),
				"png",
				FileUtil.byteToImage(rs.getBytes("image")));
	}
}
